package tech.summerly.weather.component.activities

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Gravity
import android.view.View
import com.takusemba.rtmppublisher.Publisher
import com.takusemba.rtmppublisher.PublisherListener
import kotlinx.android.synthetic.main.activity_stream_push.*
import tech.summerly.weather.R
import tech.summerly.weather.util.toast

/**
 * before start this activity , music check permission first
 */
class StreamPushActivity : AppCompatActivity() {


    private var publisher: Publisher? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_stream_push)
        publisher = Publisher.Builder(this@StreamPushActivity)
                .setUrl(SettingsActivity.getPushUrl())
                .setGlView(glSurface)
                .setVideoBitrate(1000_000)
                .setListener(publisherListener)
                .build()
        buttonPush.setOnClickListener(onPushButtonClick)
        toggleCamera.setOnClickListener {
            publisher?.switchCamera()
        }
    }

    private val publisherListener = object : PublisherListener {

        override fun onFailedToConnect() {
            toast(getString(R.string.failed_connect_stream_service)).setGravity(Gravity.CENTER, 0, 0)
        }

        override fun onStarted() {
            buttonPush.setText(getString(R.string.stop_stream))
        }

        override fun onDisconnected() {

        }

        override fun onStopped() {
            buttonPush.setText(getString(R.string.start_stream))
        }

    }


    private val onPushButtonClick = fun(_: View) {
        val publisher = this.publisher ?: return
        if (publisher.isPublishing) {
            publisher.stopPublishing()
        } else {
            publisher.startPublishing()
        }
    }
}